package yxy.game.pm2.active.command.challenge;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.handle.Act_TimeChallengeHandle;
import yxy.game.pm2.active.module.ActiveModule_限时挑战;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.ArrayList;

/** 限时挑战 挑战执行 */
@MessageType(proto = Command.ActChanllengeExecute, classtype = ActiveMessage.ActChanllengeExecuteRequest.class)
public class CMD_Active_限时挑战_ChanllengeExecute extends Command<ActiveMessage.ActChanllengeExecuteRequest> {

	@Override
	public void execute(MessageSource messageSource, ActiveMessage.ActChanllengeExecuteRequest request) {
		String playerCode = messageSource.getTag();
		BattleMessage.BattleExecuteRequest battleReq = request.getBattleReq();

		ActiveMessage.ActChanllengeExecuteResponse.Builder response = ActiveMessage.ActChanllengeExecuteResponse.newBuilder();

		Act_TimeChallengeHandle handle = new Act_TimeChallengeHandle();
		
		ActiveModule_限时挑战 am = ActiveModule_限时挑战.get(playerCode,false);
		if(am == null) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
		
		if(!am.running()) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
		
		try {
			
			handle.ActBattleResponseExecute(response, playerCode, battleReq);
//			response.setBattleResp(handle.battleResponseExecute(playerCode, battleReq));
			send(messageSource, response, Result.Success);
			
			if(response.getBattleResp().getPlayback().getResult() == 1) {
				
				if(am.getGetrewardids().contains(response.getId())) {
					return;
				}
				
				//玩家战斗胜利
				if(!am.getVictoryids().contains(response.getId())) {
					am.getVictoryids().add(response.getId());
				}
				
				if(!am.getGetrewardids().contains(response.getId())) {
					am.getGetrewardids().add(response.getId());
				}
				
				am.set();
				
				ArrayList<Currency> curs = new ArrayList<Currency>();
				for(PackageMessage.Item item : response.getRewardsList()) {
					Currency cur = Currency.create(item.getType(), item.getDataId(), item.getNumber());
					curs.add(cur);
				}
				
				if(curs.size() != 0) {
					new CurrencyHandle().addCurrency(playerCode, CCReason.活动_限时挑战, curs);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
		
		
	}

	private void send(MessageSource messageSource, ActiveMessage.ActChanllengeExecuteResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}